package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(path = "/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping(path = "/findPage")
    public Result findPage(QueryPageBean queryPageBean) {
        try {
            PageResult pageResult = memberService.pageQuery(queryPageBean);
            return new Result(true, MessageConstant.QUERY_Member_SUCCESS, pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_Member_FAIL);
        }
    }

    @PostMapping(path = "/add")
    public Result add(@RequestBody Member member) {
        try {
            memberService.add(member);
            return new Result(true, MessageConstant.ADD_Member_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_Member_FAIL);
        }
    }

    @GetMapping(path = "/{id}")
    public Result findById(@PathVariable Integer id) {
        try {
            Member member = memberService.findById(id);
            return new Result(true, MessageConstant.QUERY_Member_SUCCESS, member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_Member_FAIL);
        }
    }

    @PutMapping(path = "/edit")
    public Result update(@RequestBody Member member) {
        try {
            //查询检查项
            memberService.update(member);
            return new Result(true, MessageConstant.EDIT_Member_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_Member_FAIL);
        }
    }

    @DeleteMapping(path = "/{id}")
    public Result deleteById(@PathVariable Integer id) {
        try {
            //查询检查项
            memberService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_Member_SUCCESS);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_Member_FAIL);
        }
    }

    @RequestMapping(path = "/export")
    public Result exportBusiness(@RequestBody List<Member> list) {
        List<Integer> ins = new ArrayList<>();
        try {
            for (Member member : list) {
                ins.add(member.getId());
            }
            jedisPool.getResource().set("会员id", String.valueOf(ins));
            jedisPool.getResource().expire("会员id", 60 * 2);
            return new Result(true, MessageConstant.EXCEL_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EXCEL_FAIL, null);
        }
    }

    @RequestMapping(path = "/exportFile")
    public Result export1(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获得Excel模板文件绝对路径
            String temlateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "memberMessage.xlsx";
            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            //定义行变量
            int line = 1;
            XSSFRow row = null;
            //从 redis中获取id
            String codeInRedis = jedisPool.getResource().get("会员id");
            String s1 = codeInRedis.substring(1, codeInRedis.length() - 1);
            String[] split = s1.split(",");
            for (String s : split) {
                //多表查询封装进会员对象 中间包含套餐 检查项 检查组
                Member member = memberService.selectMemberCountSetmeal(s);
             // System.out.println(member);
                row = sheet.createRow(line++);
                row.createCell(0).setCellValue(member.getName());
                if (member.getSex() != null) {
                    switch (member.getSex()) {
                        case "1":
                            row.createCell(1).setCellValue("男");
                            break;
                        case "2":
                            row.createCell(1).setCellValue("女");
                            break;
                        default:
                            row.createCell(1).setCellValue("未填写");
                            break;
                    }
                } else {
                    row.createCell(1).setCellValue("未填写");
                }
                row.createCell(2).setCellValue(member.getPhoneNumber());
                List<Setmeal> setmeals = member.getSetmeals();
                //如果没有套餐 就不写入
                if (setmeals != null && setmeals.size() != 0) {
                    String setmeastr = "";
                    String checkGroups = "";
                    String checkItems = "";
                    //遍历获取各个套餐和检查项 检查组
                    for (Setmeal setmeal : setmeals) {
                        setmeastr = setmeastr + setmeal.getName();
                        for (CheckGroup group : setmeal.getCheckGroups()) {
                            checkGroups = checkGroups + group.getName();
                            for (CheckItem checkItem : group.getCheckItems()) {
                                checkItems = checkItems + checkItem.getName();
                            }
                        }
                    }
                    row.createCell(3).setCellValue(setmeastr);
                    row.createCell(4).setCellValue(checkGroups);
                    row.createCell(5).setCellValue(checkItems);
                }
            }
            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("content-Disposition", "attachment;filename=member.xlsx");
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            return new Result(true, MessageConstant.EXCEL_SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EXCEL_FAIL, null);
        }
    }


}
